#!/usr/bin/env python

CONTACT = 'sykp241095@gmail.com'

import sys
import os
import re
import shutil
import pysvn

if len(sys.argv) != 2:
    print 'argc error'
    sys.exit(1)

url = sys.argv[1]

if not re.match('^file:///.*$', url):
    print 'url error'
    sys.exit(1)

def main():
    svn = pysvn.Client()
    RE_DIR = re.compile("Failed to add directory '([^']+)':")
    RE_FILE = re.compile("Failed to add file '([^']+)':")
    retrys = 0
    
    while retrys < 3:
        retrys += 1
        try:
            svn.switch('.', sys.argv[1])
        except pysvn.ClientError, err:
            res_dirs = RE_DIR.findall(str(err))
            res_files = RE_FILE.findall(str(err))
            if res_dirs or res_files:
                try:
                    for file_ in res_files:
                        print 'try to delete file %s' % file_
                        os.remove(file_)
                    for dir_ in res_dirs:
                        print 'try to delete dir %s' % dir_
                        shutil.rmtree(dir_)
                except Exception, msg:
                    print 'critical error: %s' % msg
                    return 1
            else:
                print err
                return 1
        else:
            print 'switch succefully'
            return 0

    print 'switch failed'
    return 1

if __name__ == '__main__':
    sys.exit(main())

